import { login as adminLogin } from 'api/admin'
import {
  getToken,
  setToken,
  removeToken,
  getStorage,
  setStorage,
  rmStorage
} from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { toEncrypt } from '@/utils'
// import { MessageBox, Notification } from 'element-ui'
// import { HubConnectionBuilder } from '@aspnet/signalr'
const userInfo = {
  id: '',
  trueName: '',
  avatar: '',
  isAdmin: '',
  isSuperAdmin: '',
  departmentId: null,
  socket: null
}
// let socket = null
function getUserInfo() {
  return new Promise((resolve, reject) => {
    try {
      let info = {
        ...userInfo
      }
      for (const key in info) {
        info[key] = getStorage(key)
      }
      resolve(info)
    } catch (err) {
      reject(err)
    }
  })
}
function setUserInfo(info) {
  for (const key in userInfo) {
    let val = info[key]
    if (val !== undefined) {
      setStorage(key, typeof val === 'object' ? JSON.stringify(val) : val)
    }
  }
}
function rmUserInfo() {
  for (const key in userInfo) {
    rmStorage(key)
  }
}

const getDefaultState = () => {
  return {
    token: getToken(),
    ...userInfo
  }
}
const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    if (state.socket) {
      state.socket.stop()
    }
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_NAME: (state, trueName) => {
    state.trueName = trueName
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ISADMIN: (state, isAdmin) => {
    state.isAdmin = isAdmin
  },
  SET_SOCKET: (state, socket) => {
    state.socket = socket
  }
}

const actions = {
  // user login
  login({ commit }, { userName, password }) {
    return new Promise((resolve, reject) => {
      adminLogin({ userName: userName.trim(), password: toEncrypt(password) })
        .then((response) => {
          window.flag401 = false
          const { data } = response
          const encode = JSON.stringify({
            Token: data.token,
            userId: data.userId
          })
          let token = btoa(encode)
          commit('SET_TOKEN', token)
          setToken(token)
          setUserInfo(data)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then((userInfo) => {
          commit('SET_ID', userInfo.id)
          commit('SET_NAME', userInfo.trueName)
          commit('SET_AVATAR', userInfo.avatar)
          commit('SET_ISADMIN', userInfo.isAdmin)
          // if (userInfo.isAdmin == 'false' && userInfo.id) {
          //   if (window.$ && window.$.connection) {
          //     // 连接signalR
          //     let socket = window.$.connection(
          //       `${process.env.VUE_APP_PROXY_URL}/signalr`,
          //       {
          //         id: userInfo.id,
          //         source: 'tengen',
          //         ts: new Date().getTime()
          //       }
          //     )
          //     socket
          //       .start()
          //       .done(() => {})
          //       .fail(function(err) {
          //         console.log(err)
          //       })
          //     socket.received((res) => {
          //       if (res.Category === '退出登录') {
          //         MessageBox.alert(res.Data, '提醒', {
          //           confirmButtonText: '退出',
          //           type: 'warning',
          //           showClose: false
          //         }).then(() => {
          //           dispatch('resetToken').then(() => {
          //             // 跳转到登录页
          //             router.replace({
          //               path: '/login',
          //               query: { redirect: router.currentRoute.fullPath }
          //             })
          //           })
          //         })
          //       } else if (res.Category === '待办事项') {
          //         Notification.info({
          //           title: res.Category,
          //           message: res.Data,
          //           duration: 0
          //         })
          //       }
          //     })
          //     commit('SET_SOCKET', socket)
          //   }
          // }
          resolve(userInfo)
        })
        .catch(reject)
    })
  },

  // user logout
  logout({ commit }) {
    return new Promise((resolve) => {
      // logout(state.token)
      // .then(() => {
      removeToken() // must remove  token  first
      resetRouter()
      rmUserInfo()
      commit('RESET_STATE')
      resolve()
      // })
      // .catch((error) => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {
      root: true
    })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    // dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
